package com.unicloud.medical.minio.autoconfigure;

import com.unicloud.medical.minio.MinioService;
import com.unicloud.medical.minio.starter.MinioHealthCheckStarter;
import com.unicloud.medical.oss.common.beanFactoryPostProcessor.AbstractBeanFactoryPostProcessor;
import com.unicloud.medical.oss.common.constant.OSSTypeConstant;
import com.unicloud.medical.oss.common.model.OSSServerProperties;
import com.unicloud.medical.oss.common.util.CommonUtil;
import io.minio.MinioClient;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ConfigurableApplicationContext;

public class MinioBeanFactoryPostProcessor extends AbstractBeanFactoryPostProcessor {

    public MinioBeanFactoryPostProcessor(ConfigurableApplicationContext applicationContext, String ossType) {
        super(applicationContext, ossType);
    }

    @Override
    protected String type() {
        return OSSTypeConstant.MINIO;
    }

    @Override
    protected void registerClient(OSSServerProperties ossServerProperties, BeanDefinitionRegistry registry) throws Exception {
        // MinioClient
        MinioClient minioClient = MinioClient.builder()
                .endpoint(ossServerProperties.getEndpoint())
                .credentials(ossServerProperties.getAccessKey(), ossServerProperties.getSecretKey())
                .build();

        String name = CommonUtil.buildName(ossServerProperties.getName(), "minio", ossServerProperties.getEndpoint());

        // MinioService
        registerBeanDefinition(registry, name + "MinioService",
                BeanDefinitionBuilder
                        .genericBeanDefinition(MinioService.class)
                        .addPropertyValue("name", name)
                        .addPropertyValue("minioProperties", ossServerProperties)
                        .addPropertyValue("minioClient", minioClient)
                        .getBeanDefinition());

        // MinioHealthCheckStarter
        registerBeanDefinition(registry, name + "MinioHealthCheckStarter",
                BeanDefinitionBuilder
                        .genericBeanDefinition(MinioHealthCheckStarter.class)
                        .addPropertyValue("minioClient", minioClient)
                        .addPropertyValue("check", ossServerProperties.getCheck())
                        .getBeanDefinition());
    }
}
